<template>
  <div class="mind-map-container">
    <div ref="mindMapContainer" class="mind-map-canvas"></div>

    <!-- 右键菜单 -->
    <div
      ref="contextMenu"
      class="context-menu"
      v-show="contextMenuVisible"
      :style="contextMenuStyle"
      @click.stop
    >
      <div class="context-menu-item" @click="_insertSiblingNode">
        <span class="menu-icon">⊞</span>
        <span class="menu-text">插入同级节点</span>
      </div>
      <div class="context-menu-item" @click="_insertChildNode">
        <span class="menu-icon">└</span>
        <span class="menu-text">插入子级节点</span>
      </div>
      <div class="context-menu-item" @click="_insertParentNode">
        <span class="menu-icon">┌</span>
        <span class="menu-text">插入父级节点</span>
      </div>
      <div class="context-menu-divider"></div>
      <div class="context-menu-item danger" @click="_deleteNodeWithChildren">
        <span class="menu-icon">🗑</span>
        <span class="menu-text">删除节点</span>
      </div>
      <div class="context-menu-item danger" @click="_deleteCurrentNodeOnly">
        <span class="menu-icon">✂</span>
        <span class="menu-text">仅删除当前节点</span>
      </div>
    </div>
  </div>
</template>

<script>
import MindMap from "simple-mind-map";

export default {
  name: "Mind",
  props: {
    // 思维导图数据
    mindMapData: {
      type: Object,
      required: true,
    },
    // 主题配置
    themeConfig: {
      type: Object,
      default: () => ({}),
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    // 颜色控制模式：'level' 按层级控制，'type' 按类型控制
    colorMode: {
      type: String,
      default: "level",
      validator: (value) => ["level", "type"].includes(value),
    },
  },
  data() {
    return {
      // 响应式数据
      mindMapInstance: null,
      highlightedNodes: new Set(),

      // 右键菜单相关数据
      contextMenuVisible: false,
      contextMenuStyle: {},
      currentRightClickNode: null,

      // 性能优化：节点缓存
      nodeCache: {
        allNodes: [],
        nodeMap: new Map(), // id -> node
        nameMap: new Map(), // name -> [nodes]
        typeMap: new Map(), // type -> [nodes]
      },

      // 内部数据副本，用于动态修改
      internalMindMapData: {
        nodes: [],
        links: [],
      },

      // 存储事件处理器的引用，以便后续清理
      keyboardEventHandlers: [],
      globalEventHandlers: [],
    };
  },
  mounted() {
    // 等待下一个tick再初始化，确保props已经传入
    this.$nextTick(() => {
      this._initInternalData(this.mindMapData);
      this._initMindMap(this.internalMindMapData);
    });
  },
  beforeUnmount() {
    // 清理键盘事件监听器
    this._cleanupKeyboardEventListeners();

    // 清理全局事件监听器
    this._cleanupGlobalEventListeners();

    // 销毁思维导图实例
    if (this.mindMapInstance) {
      try {
        this.mindMapInstance.destroy();
      } catch (error) {
        console.error("销毁思维导图实例时出错:", error);
      }
    }

    console.log("Mind组件已卸载，所有资源已清理");
  },
  watch: {
    mindMapData: {
      handler(newData) {
        if (newData) {
          // 更新内部数据副本
          this._initInternalData(newData);

          // 如果思维导图已初始化，则重新渲染
          if (this.mindMapInstance) {
            const convertedData = this._convertToMindMapData(
              this.internalMindMapData
            );
            if (convertedData) {
              this.mindMapInstance.setData(convertedData);
              this.mindMapInstance.render();
              setTimeout(() => {
                // 重新计算缓存以确保数据一致性
                this._buildNodeCache();
              }, 100);
            }
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 初始化思维导图
    async _initMindMap(mindMapData) {
      if (!this.$refs.mindMapContainer) return;

      // 检查数据是否存在
      if (!mindMapData || !mindMapData.nodes || !mindMapData.links) {
        console.warn("等待mindMapData数据...");
        return;
      }

      try {
        // 转换数据
        const convertedData = this._convertToMindMapData(mindMapData);

        if (!convertedData) {
          console.error("数据转换失败");
          return;
        }

        // 默认主题配置
        const defaultThemeConfig = {
          root: {
            shape: "rectangle",
            fillColor: "#4A90E2",
            borderWidth: 0,
            color: "#ffffff",
            fontSize: 16,
            fontWeight: 600,
            paddingX: 20,
            paddingY: 12,
            borderRadius: 8,
          },
          second: {
            shape: "rectangle",
            fillColor: "#7ED321",
            borderWidth: 0,
            color: "#ffffff",
            fontSize: 14,
            fontWeight: 500,
            paddingX: 16,
            paddingY: 10,
            borderRadius: 6,
          },
          node: {
            shape: "rectangle",
            fillColor: "#F5A623",
            borderWidth: 0,
            color: "#ffffff",
            fontSize: 12,
            fontWeight: 400,
            paddingX: 12,
            paddingY: 8,
            borderRadius: 4,
          },
          line: {
            width: 2,
            color: "#4A90E2",
            activeWidth: 3,
            activeColor: "#2E7BD4",
          },
        };

        // 深度合并主题配置
        const mergeThemeConfig = (defaultConfig, customConfig) => {
          const merged = { ...defaultConfig };

          for (const key in customConfig) {
            if (Object.prototype.hasOwnProperty.call(customConfig, key)) {
              if (
                typeof customConfig[key] === "object" &&
                customConfig[key] !== null &&
                typeof defaultConfig[key] === "object" &&
                defaultConfig[key] !== null
              ) {
                // 深度合并对象
                merged[key] = { ...defaultConfig[key], ...customConfig[key] };
              } else {
                // 直接赋值
                merged[key] = customConfig[key];
              }
            }
          }

          return merged;
        };

        const finalThemeConfig = mergeThemeConfig(
          defaultThemeConfig,
          this.themeConfig
        );

        // 创建思维导图实例
        this.mindMapInstance = new MindMap({
          el: this.$refs.mindMapContainer,
          data: convertedData,
          themeConfig: finalThemeConfig,
          openPerformance: true,
          // 编辑模式配置
          readonly: !this.isEdit,
          // 禁用双击编辑节点文本
          enableNodeTextEditOnDoubleClick: false,
        });

        // 绑定事件
        this._bindMindMapEvents();

        // 添加全局点击事件监听器，用于隐藏右键菜单
        this._addGlobalEventListeners();

        // 彻底禁用键盘快捷键
        this._disableAllKeyboardShortcuts();

        // 彻底禁用节点编辑功能
        this._disableNodeEditing();

        // 初始化完成后居中显示
        setTimeout(() => {
          if (this.mindMapInstance) {
            this.mindMapInstance.view.fit();

            // 重新计算缓存以确保数据一致性
            this._buildNodeCache();

            // 根据颜色模式应用样式
            if (this.colorMode === "type") {
              this._applyNodeTypeStyles();
            }
          }
        }, 100);
      } catch (error) {
        console.error("思维导图初始化失败:", error);
      }
    },

    // 初始化内部数据副本
    _initInternalData(mindMapData) {
      if (mindMapData && mindMapData.nodes && mindMapData.links) {
        this.internalMindMapData = {
          nodes: [...mindMapData.nodes],
          links: [...mindMapData.links],
        };
      }
    },

    // 转换网络图数据为思维导图数据格式
    _convertToMindMapData(mindMapData) {
      if (!mindMapData || !mindMapData.nodes || !mindMapData.links) {
        console.warn("思维导图数据不完整或为空");
        return null;
      }
      const { nodes, links } = mindMapData;

      // 创建节点映射
      const nodeMap = new Map();
      nodes.forEach((node) => {
        nodeMap.set(node.id, {
          ...node,
          children: [],
        });
      });

      // 根据连接关系构建层次结构
      const childrenMap = new Map();
      links.forEach((link) => {
        if (!childrenMap.has(link.source)) {
          childrenMap.set(link.source, []);
        }
        childrenMap.get(link.source).push({
          targetId: link.target,
          label: link.label,
        });
      });

      // 递归构建思维导图结构
      const buildMindMapNode = (nodeId, visited = new Set()) => {
        if (visited.has(nodeId)) {
          // 避免循环引用，返回简化节点
          const node = nodeMap.get(nodeId);
          return {
            data: {
              uid: node.id,
              text: node.label,
              type: node.type,
            },
          };
        }

        visited.add(nodeId);
        const node = nodeMap.get(nodeId);
        if (!node) return null;

        const mindMapNode = {
          data: {
            uid: node.id,
            text: node.label,
            type: node.type,
          },
          children: [],
        };

        // 获取子节点
        const children = childrenMap.get(nodeId) || [];
        children.forEach((child) => {
          const childNode = buildMindMapNode(child.targetId, new Set(visited));
          if (childNode) {
            mindMapNode.children.push(childNode);
          }
        });

        visited.delete(nodeId);
        return mindMapNode;
      };

      // 动态找到根节点（层次结构中最上层的节点）
      const findRootNode = () => {
        // 统计每个节点作为父节点的次数和深度
        const nodeStats = new Map();
        nodes.forEach((node) => {
          nodeStats.set(node.id, {
            asParent: 0,
            asChild: 0,
            level: 0,
          });
        });

        // 统计父子关系
        links.forEach((link) => {
          if (nodeStats.has(link.source)) {
            nodeStats.get(link.source).asParent++;
          }
          if (nodeStats.has(link.target)) {
            nodeStats.get(link.target).asChild++;
          }
        });

        // 找到最可能的根节点：
        // 1. 优先选择从未作为子节点的节点（没有父节点）
        // 2. 如果都有父节点，选择作为父节点次数最多的
        let rootCandidates = [];

        // 首先找没有父节点的节点
        for (const [nodeId, stats] of nodeStats) {
          if (stats.asChild === 0) {
            rootCandidates.push({ nodeId, stats });
          }
        }

        // 如果没有找到没有父节点的节点，选择作为父节点次数最多的
        if (rootCandidates.length === 0) {
          let maxAsParent = 0;
          for (const [nodeId, stats] of nodeStats) {
            if (stats.asParent > maxAsParent) {
              maxAsParent = stats.asParent;
              rootCandidates = [{ nodeId, stats }];
            } else if (stats.asParent === maxAsParent && stats.asParent > 0) {
              rootCandidates.push({ nodeId, stats });
            }
          }
        }

        // 如果还是没有合适的候选者，选择第一个节点
        if (rootCandidates.length === 0 && nodes.length > 0) {
          return nodes[0].id;
        }

        // 从候选者中选择第一个
        return rootCandidates.length > 0 ? rootCandidates[0].nodeId : null;
      };

      const rootNodeId = findRootNode();
      if (!rootNodeId) {
        console.warn("无法找到根节点");
        return null;
      }

      console.log("选择的根节点:", rootNodeId);
      return buildMindMapNode(rootNodeId);
    },

    // 绑定思维导图事件
    _bindMindMapEvents() {
      if (!this.mindMapInstance) return;

      // 用于防止事件冒泡的标记
      let isNodeClicked = false;

      // 节点的单击事件
      this.mindMapInstance.on("node_click", (node) => {
        isNodeClicked = true;

        if (node?.uid) {
          this.highlightNodeAndChildrenByNodeId(node.uid);
        }

        // 重置标记，延迟一点确保其他事件处理完成
        setTimeout(() => {
          isNodeClicked = false;
        }, 10);
      });

      // 节点的双击事件
      this.mindMapInstance.on("node_dblclick", (node, e) => {
        console.log("节点的双击事件:", node);
        isNodeClicked = true;

        // 阻止默认的双击编辑行为
        if (e && typeof e.preventDefault === "function") {
          e.preventDefault();
          e.stopPropagation();
        }

        // 确保不进入编辑模式
        if (this.mindMapInstance && this.mindMapInstance.renderer) {
          // 取消任何可能的文本编辑状态
          this.mindMapInstance.renderer.textEdit?.hideEditTextBox();
        }

        console.log("双击编辑已被禁用");

        // 重置标记
        setTimeout(() => {
          isNodeClicked = false;
        }, 10);
      });

      // 节点的右键事件
      this.mindMapInstance.on("node_contextmenu", (e, node) => {
        e.preventDefault(); // 阻止默认右键菜单
        e.stopPropagation(); // 阻止事件冒泡

        // 获取鼠标位置
        const { clientX: x, clientY: y } = e;

        // 显示自定义右键菜单
        this._showContextMenu(x, y, node);
      });

      // 渲染树数据变化，可以监听该方法获取最新数据
      this.mindMapInstance.on("data_change", (data) => {
        console.log("渲染树数据变化:", data);
      });

      // 节点文本编辑框显示事件 - 强制禁用编辑
      this.mindMapInstance.on("show_text_edit", (node, textEditElement) => {
        console.log("检测到文本编辑尝试，已被禁用", node);

        // 立即隐藏编辑框
        if (
          this.mindMapInstance &&
          this.mindMapInstance.renderer &&
          this.mindMapInstance.renderer.textEdit
        ) {
          // 使用setTimeout确保在下一个事件循环中执行，避免时序问题
          setTimeout(() => {
            this.mindMapInstance.renderer.textEdit.hideEditTextBox();
          }, 0);
        }

        // 如果有传入的编辑元素，直接隐藏
        if (textEditElement && textEditElement.style) {
          textEditElement.style.display = "none";
        }
      });

      // 节点文本编辑框关闭事件
      this.mindMapInstance.on(
        "hide_text_edit",
        (textEditNode, activeNodeList, node) => {
          console.log(
            "节点文本编辑框关闭事件:",
            textEditNode,
            activeNodeList,
            node
          );
        }
      );

      // 节点树渲染完毕事件
      this.mindMapInstance.on("node_tree_render_end", () => {
        // 渲染完成后根据颜色模式应用样式
        // 注意：这里需要应用全部节点样式，因为可能是数据切换或初始化
        if (this.colorMode === "type") {
          setTimeout(() => {
            this._applyNodeTypeStyles();
          }, 50);
        }
      });

      // 画布的单击事件
      this.mindMapInstance.on("draw_click", () => {
        // 如果是节点点击触发的冒泡事件，则忽略
        if (isNodeClicked) {
          return;
        }

        this.clearHighlight();
        // 隐藏右键菜单
        this._hideContextMenu();
      });
    },

    // 添加全局事件监听器
    _addGlobalEventListeners() {
      // 全局点击事件：点击空白处隐藏右键菜单
      const globalClickHandler = (e) => {
        // 检查点击是否在右键菜单内部
        if (
          this.$refs.contextMenu &&
          this.$refs.contextMenu.contains(e.target)
        ) {
          return; // 点击在菜单内部，不隐藏
        }

        // 检查点击是否在思维导图容器内部
        if (
          this.$refs.mindMapContainer &&
          this.$refs.mindMapContainer.contains(e.target)
        ) {
          return; // 点击在思维导图内部，由其他事件处理
        }

        // 点击在外部，隐藏菜单
        this._hideContextMenu();
      };

      // 添加事件监听器
      document.addEventListener("click", globalClickHandler, true);

      // 保存处理器引用以便清理
      this.globalEventHandlers.push({
        element: document,
        event: "click",
        handler: globalClickHandler,
      });
    },

    // 清理全局事件监听器
    _cleanupGlobalEventListeners() {
      this.globalEventHandlers.forEach(({ element, event, handler }) => {
        element.removeEventListener(event, handler, true);
      });
      this.globalEventHandlers = [];
    },

    // 彻底禁用所有键盘快捷键
    _disableAllKeyboardShortcuts() {
      if (!this.mindMapInstance) return;

      try {
        // 方法1: 尝试禁用keyCommand（如果存在的话）
        if (
          this.mindMapInstance.keyCommand &&
          typeof this.mindMapInstance.keyCommand.disable === "function"
        ) {
          this.mindMapInstance.keyCommand.disable();
        } else if (
          this.mindMapInstance.command &&
          typeof this.mindMapInstance.command.disableShortcuts === "function"
        ) {
          this.mindMapInstance.command.disableShortcuts();
        }

        // 通用的键盘事件阻止函数
        const preventKeyboard = (e) => {
          // 更全面的快捷键列表
          const isShortcut =
            e.key === "Delete" ||
            e.key === "Backspace" ||
            e.key === "Tab" ||
            e.key === "Enter" ||
            e.key === "Escape" ||
            e.key === "F2" ||
            e.key === "Insert" ||
            (e.ctrlKey && (e.key === "c" || e.key === "C")) ||
            (e.ctrlKey && (e.key === "v" || e.key === "V")) ||
            (e.ctrlKey && (e.key === "x" || e.key === "X")) ||
            (e.ctrlKey && (e.key === "z" || e.key === "Z")) ||
            (e.ctrlKey && (e.key === "y" || e.key === "Y")) ||
            (e.ctrlKey && (e.key === "a" || e.key === "A")) ||
            (e.ctrlKey && (e.key === "d" || e.key === "D")) ||
            (e.ctrlKey && (e.key === "s" || e.key === "S")) ||
            (e.ctrlKey && e.shiftKey && (e.key === "z" || e.key === "Z")) ||
            (e.altKey && e.key === "F4") ||
            // 方向键组合
            (e.ctrlKey &&
              ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(
                e.key
              )) ||
            (e.shiftKey &&
              ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(
                e.key
              )) ||
            // F功能键
            [
              "F1",
              "F2",
              "F3",
              "F4",
              "F5",
              "F6",
              "F7",
              "F8",
              "F9",
              "F10",
              "F11",
              "F12",
            ].includes(e.key) ||
            // 其他常见快捷键
            (e.key === " " && e.ctrlKey) || // Ctrl+Space
            e.key === "Home" ||
            e.key === "End" ||
            e.key === "PageUp" ||
            e.key === "PageDown";

          if (isShortcut) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            const shortcutDesc =
              e.ctrlKey || e.altKey || e.shiftKey
                ? `${e.ctrlKey ? "Ctrl+" : ""}${e.altKey ? "Alt+" : ""}${
                    e.shiftKey ? "Shift+" : ""
                  }${e.key}`
                : e.key;
            return false;
          }
        };

        // 检查是否在思维导图区域内的函数
        const isInMindMapArea = () => {
          const activeElement = document.activeElement;
          const container = this.$refs.mindMapContainer;

          if (!container) return false;

          return (
            container.contains(activeElement) ||
            activeElement === container ||
            container.querySelector("svg") === activeElement ||
            activeElement?.closest(".mind-map-container") === container
          );
        };

        // 全局键盘事件处理器
        const globalKeyHandler = (e) => {
          if (isInMindMapArea()) {
            preventKeyboard(e);
          }
        };

        // 容器键盘事件处理器
        const containerKeyHandler = (e) => {
          preventKeyboard(e);
        };

        // 在思维导图容器上添加键盘事件拦截
        const container = this.$refs.mindMapContainer;
        if (container) {
          container.addEventListener("keydown", containerKeyHandler, true);
          container.addEventListener("keyup", containerKeyHandler, true);
          container.addEventListener("keypress", containerKeyHandler, true);

          // 确保容器可以接收键盘事件
          container.tabIndex = -1;

          // 保存处理器引用
          this.keyboardEventHandlers.push(
            {
              element: container,
              event: "keydown",
              handler: containerKeyHandler,
            },
            {
              element: container,
              event: "keyup",
              handler: containerKeyHandler,
            },
            {
              element: container,
              event: "keypress",
              handler: containerKeyHandler,
            }
          );
        }

        // 在document级别添加全局拦截
        document.addEventListener("keydown", globalKeyHandler, true);
        document.addEventListener("keyup", globalKeyHandler, true);

        // 保存全局处理器引用
        this.keyboardEventHandlers.push(
          { element: document, event: "keydown", handler: globalKeyHandler },
          { element: document, event: "keyup", handler: globalKeyHandler }
        );
      } catch (error) {
        console.error("禁用键盘快捷键时出错:", error);
      }
    },

    // 清理键盘事件监听器
    _cleanupKeyboardEventListeners() {
      this.keyboardEventHandlers.forEach(({ element, event, handler }) => {
        element.removeEventListener(event, handler, true);
      });
      this.keyboardEventHandlers = [];
    },

    // 彻底禁用节点编辑功能
    _disableNodeEditing() {
      if (!this.mindMapInstance) return;

      try {
        // 方法1: 直接禁用textEdit实例
        if (
          this.mindMapInstance.renderer &&
          this.mindMapInstance.renderer.textEdit
        ) {
          const textEdit = this.mindMapInstance.renderer.textEdit;

          // 重写showEditTextBox方法使其无效
          textEdit.showEditTextBox = () => {
            return false;
          };

          // 重写show方法使其无效
          textEdit.show = () => {
            return false;
          };

          // 确保编辑框始终隐藏
          textEdit.hideEditTextBox && textEdit.hideEditTextBox();
        }

        // 方法2: 禁用相关配置
        if (this.mindMapInstance.opt) {
          this.mindMapInstance.opt.enableNodeTextEditOnDoubleClick = false;
        }

        // 方法3: 拦截所有可能的编辑触发方式
        const originalExecCommand = this.mindMapInstance.execCommand;
        this.mindMapInstance.execCommand = function (name, ...args) {
          // 阻止文本编辑相关的命令
          if (
            name === "TEXT_EDIT" ||
            name === "START_TEXT_EDIT" ||
            name === "EDIT_NODE_TEXT"
          ) {
            return false;
          }
          // 其他命令正常执行
          return originalExecCommand.call(this, name, ...args);
        };
      } catch (error) {
        console.error("禁用节点编辑时出错:", error);
      }
    },

    // 根据节点类型获取颜色配置
    _getNodeColorByType(type) {
      // 从 themeConfig 中获取类型颜色配置
      const typeColors = this.themeConfig.typeColors || {};
      return (
        typeColors[type] || {
          fillColor: "#50E3C2",
          textColor: "#ffffff",
        }
      );
    },

    // 应用节点类型样式（全部节点）
    _applyNodeTypeStyles() {
      if (!this.mindMapInstance) return;

      const root = this.mindMapInstance.renderer?.root;
      if (!root) return;

      const allNodes = this._getAllNodes(root);

      allNodes.forEach((node) => {
        this._applySingleNodeTypeStyle(node);
      });
    },

    // 应用单个节点类型样式
    _applySingleNodeTypeStyle(node) {
      if (!node) {
        console.warn("节点为空，无法应用样式");
        return;
      }
      const nodeType = node.nodeData?.data?.type;
      if (!nodeType) {
        console.warn("节点类型为空:", node.uid);
        return;
      }

      const nodeElement = node.group?.node;
      if (!nodeElement) {
        console.warn("节点元素为空:", node.uid);
        return;
      }

      const colorConfig = this._getNodeColorByType(nodeType);

      // 获取节点的形状元素和文本元素
      const shapeElement = nodeElement.querySelector(".smm-node-shape");

      if (shapeElement) {
        shapeElement.style.fill = colorConfig.fillColor;
      } else {
        console.warn(`  - 未找到形状元素`);
      }

      // 保存类型信息到元素属性，便于后续查询
      nodeElement.setAttribute("data-node-type", nodeType);
    },

    // 递归获取所有节点
    _getAllNodes(node, nodes = []) {
      if (!node) return nodes;

      nodes.push(node);
      if (node.children && node.children.length > 0) {
        node.children.forEach((child) => {
          this._getAllNodes(child, nodes);
        });
      }
      return nodes;
    },

    // 性能优化：构建节点缓存
    _buildNodeCache() {
      if (!this.mindMapInstance) return this.nodeCache;

      const root = this.mindMapInstance.renderer?.root;
      if (!root) return this.nodeCache;
      this._clearNodeCache();
      const allNodes = this._getAllNodes(root);
      const nodeMap = new Map();
      const nameMap = new Map();
      const typeMap = new Map();

      allNodes.forEach((node) => {
        const nodeId = node.uid;
        const nodeName = node.nodeData?.data?.text || "";
        const nodeType = node.nodeData?.data?.type || "";

        // 构建ID映射
        nodeMap.set(nodeId, node);

        // 构建名称映射
        if (nodeName) {
          if (!nameMap.has(nodeName)) {
            nameMap.set(nodeName, []);
          }
          nameMap.get(nodeName).push(node);
        }

        // 构建类型映射
        if (nodeType) {
          if (!typeMap.has(nodeType)) {
            typeMap.set(nodeType, []);
          }
          typeMap.get(nodeType).push(node);
        }
      });

      this.nodeCache = {
        allNodes,
        nodeMap,
        nameMap,
        typeMap,
      };
      return this.nodeCache;
    },

    // 清空节点缓存
    _clearNodeCache() {
      this.nodeCache = {
        allNodes: [],
        nodeMap: new Map(),
        nameMap: new Map(),
        typeMap: new Map(),
      };
    },

    // 通用节点查找方法
    _findNodesByCondition(condition, collectChildren = false) {
      const cache = this.nodeCache;
      const targetNodes = [];
      const highlightNodeIds = new Set();

      // 根据条件查找节点
      if (condition.type === "id") {
        const nodeIds = Array.isArray(condition.value)
          ? condition.value
          : [condition.value];
        nodeIds.forEach((id) => {
          const node = cache.nodeMap.get(id);
          if (node) targetNodes.push(node);
        });
      } else if (condition.type === "name") {
        const nodeNames = Array.isArray(condition.value)
          ? condition.value
          : [condition.value];
        nodeNames.forEach((name) => {
          // 支持模糊匹配
          cache.nameMap.forEach((nodes, mapName) => {
            if (mapName.includes(name) || mapName === name) {
              targetNodes.push(...nodes);
            }
          });
        });
      } else if (condition.type === "type") {
        const nodeTypes = Array.isArray(condition.value)
          ? condition.value
          : [condition.value];
        nodeTypes.forEach((type) => {
          const nodes = cache.typeMap.get(type);
          if (nodes) targetNodes.push(...nodes);
        });
      }

      // 收集目标节点
      if (collectChildren) {
        // 递归收集目标节点及其所有子节点
        const collectNodeAndChildren = (node) => {
          highlightNodeIds.add(node.uid);
          if (node.children && node.children.length > 0) {
            node.children.forEach((child) => {
              collectNodeAndChildren(child);
            });
          }
        };

        targetNodes.forEach((targetNode) => {
          collectNodeAndChildren(targetNode);
        });
      } else {
        // 只收集目标节点本身
        targetNodes.forEach((node) => {
          highlightNodeIds.add(node.uid);
        });
      }

      return { targetNodes, highlightNodeIds, allNodes: cache.allNodes };
    },

    // 通用高亮应用方法
    _applyHighlight(highlightNodeIds, allNodes) {
      this.highlightedNodes = highlightNodeIds;

      // 应用样式 - 使用多种方式确保在只读模式下也能生效
      allNodes.forEach((node) => {
        const nodeElement = node.group?.node;
        if (nodeElement) {
          if (highlightNodeIds.has(node.uid)) {
            // 高亮节点 - 使用多种方式设置样式
            this._setNodeHighlightStyle(nodeElement, true);
          } else {
            // 弱化其他节点
            this._setNodeHighlightStyle(nodeElement, false);
          }
        }
      });
    },

    // 设置节点高亮样式的通用方法
    _setNodeHighlightStyle(nodeElement, isHighlight) {
      if (!nodeElement) return;

      if (isHighlight) {
        // 方法1: 添加CSS类
        nodeElement.classList.add("node-highlighted");
        nodeElement.classList.remove("node-dimmed");

        // 方法2: 直接设置内联样式作为备选方案
        const shapeElement = nodeElement.querySelector(".smm-node-shape");
        const textElement = nodeElement.querySelector(".smm-node-text");

        if (shapeElement) {
          shapeElement.style.transform = "scale(1.05)";
          shapeElement.style.boxShadow = "0 6px 20px rgba(255, 255, 255, 1)";
          shapeElement.style["stroke-width"] = "2px";
          shapeElement.style.stroke = "#fff";
          shapeElement.style.zIndex = "10";
        }

        if (textElement) {
          textElement.style.fontWeight = "700";
          textElement.style.color = "#2b6cb0";
        }

        // 方法3: 设置自定义属性用于识别
        nodeElement.setAttribute("data-highlight-state", "highlighted");
      } else {
        // 弱化节点
        nodeElement.classList.add("node-dimmed");
        nodeElement.classList.remove("node-highlighted");

        // 直接设置内联样式
        nodeElement.style.opacity = "0.3";

        const shapeElement = nodeElement.querySelector(".smm-node-shape");
        const textElement = nodeElement.querySelector(".smm-node-text");

        if (shapeElement) {
          shapeElement.style.filter = "grayscale(0.5)";
          shapeElement.style.transform = "scale(0.95)";
        }

        if (textElement) {
          textElement.style.color = "#a0aec0";
        }

        nodeElement.setAttribute("data-highlight-state", "dimmed");
      }
    },

    // 验证节点数据格式
    _validateNodeData(node) {
      if (!node || typeof node !== "object") {
        return { valid: false, error: "节点必须是一个对象" };
      }

      if (!node.id) {
        return { valid: false, error: "节点必须有id属性" };
      }

      if (!node.label) {
        return { valid: false, error: "节点必须有label属性" };
      }

      return { valid: true };
    },

    // 验证连接数据格式
    _validateLinkData(link) {
      if (!link || typeof link !== "object") {
        return { valid: false, error: "连接必须是一个对象" };
      }

      if (!link.source || !link.target) {
        return { valid: false, error: "连接必须有source和target属性" };
      }

      return { valid: true };
    },

    // ======= 右键菜单功能 =======

    // 显示右键菜单
    _showContextMenu(x, y, node) {
      if (!node) {
        console.warn("无法显示菜单：节点为空");
        return;
      }

      this.currentRightClickNode = node;

      // 计算菜单位置
      const menuPosition = this._calculateMenuPosition(x, y);

      this.contextMenuStyle = {
        left: `${menuPosition.x}px`,
        top: `${menuPosition.y}px`,
      };

      this.contextMenuVisible = true;
    },

    // 隐藏右键菜单
    _hideContextMenu() {
      this.contextMenuVisible = false;
      this.currentRightClickNode = null;
    },

    // 计算菜单位置，确保菜单不会超出视窗边界
    _calculateMenuPosition(x, y) {
      const menuWidth = 180; // 菜单宽度
      const menuHeight = 200; // 菜单高度（大致估算）

      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;

      let adjustedX = x;
      let adjustedY = y;

      // 检查右边界
      if (x + menuWidth > viewportWidth) {
        adjustedX = viewportWidth - menuWidth - 10;
      }

      // 检查左边界
      if (adjustedX < 10) {
        adjustedX = 10;
      }

      // 检查下边界
      if (y + menuHeight > viewportHeight) {
        adjustedY = viewportHeight - menuHeight - 10;
      }

      // 检查上边界
      if (adjustedY < 10) {
        adjustedY = 10;
      }

      return { x: adjustedX, y: adjustedY };
    },

    // ======= 右键菜单操作函数 =======

    // 插入同级节点
    _insertSiblingNode() {
      if (!this.currentRightClickNode) {
        console.warn("无法插入同级节点：当前节点为空");
        return;
      }

      try {
        const currentNode = this.currentRightClickNode;

        // 获取当前节点的父节点（同级节点的父节点）
        const parentNode = currentNode.parent;
        if (!parentNode) {
          console.warn("无法插入同级节点：当前节点没有父节点");
          this.$emit("node-context-menu-action", {
            action: "insertSiblingNode",
            nodeId: currentNode.uid,
            nodeText: currentNode.nodeData?.data?.text || "",
            warning: "当前节点没有父节点，无法插入同级节点",
            timestamp: new Date().toISOString(),
          });
          return;
        }

        // 激活当前节点
        this.mindMapInstance.renderer.activeNodeList = [currentNode];

        // 使用 INSERT_NODE 命令插入同级节点
        this.mindMapInstance.execCommand("INSERT_NODE", false);

        // 发送emit事件通知父组件，传递父节点信息
        this.$emit("node-context-menu-action", {
          action: "insertSiblingNode",
          currentNodeId: currentNode.uid,
          currentNodeText: currentNode.nodeData?.data?.text || "",
          parentNodeId: parentNode.uid,
          parentNodeText: parentNode.nodeData?.data?.text || "",
          parentNodeType: parentNode.nodeData?.data?.type || "",
          timestamp: new Date().toISOString(),
        });
      } catch (error) {
        console.error("插入同级节点时出错:", error);
        // 发送错误事件
        this.$emit("node-context-menu-action", {
          action: "insertSiblingNode",
          nodeId: this.currentRightClickNode?.uid || null,
          error: error.message,
          timestamp: new Date().toISOString(),
        });
      } finally {
        this._hideContextMenu();
      }
    },

    // 插入子级节点
    _insertChildNode() {
      if (!this.currentRightClickNode) {
        console.warn("无法插入子级节点：当前节点为空");
        return;
      }

      try {
        const currentNode = this.currentRightClickNode;

        // 激活当前节点
        this.mindMapInstance.renderer.activeNodeList = [currentNode];

        // 使用 INSERT_CHILD_NODE 命令插入子级节点
        this.mindMapInstance.execCommand("INSERT_CHILD_NODE", false);

        // 发送emit事件通知父组件，传递父节点（当前激活节点）信息
        this.$emit("node-context-menu-action", {
          action: "insertChildNode",
          parentNodeId: currentNode.uid,
          parentNodeText: currentNode.nodeData?.data?.text || "",
          parentNodeType: currentNode.nodeData?.data?.type || "",
          timestamp: new Date().toISOString(),
        });
      } catch (error) {
        console.error("插入子级节点时出错:", error);
        // 发送错误事件
        this.$emit("node-context-menu-action", {
          action: "insertChildNode",
          nodeId: this.currentRightClickNode?.uid || null,
          error: error.message,
          timestamp: new Date().toISOString(),
        });
      } finally {
        this._hideContextMenu();
      }
    },

    // 插入父级节点
    _insertParentNode() {
      if (!this.currentRightClickNode) {
        console.warn("无法插入父级节点：当前节点为空");
        return;
      }

      try {
        const currentNode = this.currentRightClickNode;

        // 获取当前节点的父节点（新插入父节点的父节点）
        const grandParentNode = currentNode.parent;
        if (!grandParentNode) {
          console.warn("无法插入父级节点：当前节点没有父节点");
          this.$emit("node-context-menu-action", {
            action: "insertParentNode",
            nodeId: currentNode.uid,
            nodeText: currentNode.nodeData?.data?.text || "",
            warning: "当前节点没有父节点，无法插入父级节点",
            timestamp: new Date().toISOString(),
          });
          return;
        }

        // 激活当前节点
        this.mindMapInstance.renderer.activeNodeList = [currentNode];

        // 使用 INSERT_PARENT_NODE 命令插入父级节点
        this.mindMapInstance.execCommand("INSERT_PARENT_NODE", false);

        // 发送emit事件通知父组件，传递当前节点和新插入父节点的父节点信息
        this.$emit("node-context-menu-action", {
          action: "insertParentNode",
          currentNodeId: currentNode.uid,
          currentNodeText: currentNode.nodeData?.data?.text || "",
          currentNodeType: currentNode.nodeData?.data?.type || "",
          grandParentNodeId: grandParentNode.uid,
          grandParentNodeText: grandParentNode.nodeData?.data?.text || "",
          grandParentNodeType: grandParentNode.nodeData?.data?.type || "",
          timestamp: new Date().toISOString(),
        });
      } catch (error) {
        console.error("插入父级节点时出错:", error);
        // 发送错误事件
        this.$emit("node-context-menu-action", {
          action: "insertParentNode",
          nodeId: this.currentRightClickNode?.uid || null,
          error: error.message,
          timestamp: new Date().toISOString(),
        });
      } finally {
        this._hideContextMenu();
      }
    },

    // 删除节点（包含子节点）
    _deleteNodeWithChildren() {
      if (!this.currentRightClickNode) {
        console.warn("无法删除节点：当前节点为空");
        return;
      }

      try {
        const currentNode = this.currentRightClickNode;

        // 检查是否为根节点
        if (currentNode.isRoot) {
          console.warn("无法删除根节点");
          // 发送根节点删除限制事件
          this.$emit("node-context-menu-action", {
            action: "deleteNodeWithChildren",
            nodeId: currentNode.uid,
            nodeText: currentNode.nodeData?.data?.text || "",
            warning: "无法删除根节点",
            timestamp: new Date().toISOString(),
          });
          return;
        }

        // 激活当前节点
        this.mindMapInstance.renderer.activeNodeList = [currentNode];

        // 使用 REMOVE_NODE 命令删除节点及其子节点
        this.mindMapInstance.execCommand("REMOVE_NODE");

        // 发送emit事件通知父组件
        this.$emit("node-context-menu-action", {
          action: "deleteNodeWithChildren",
          nodeId: currentNode.uid,
          nodeText: currentNode.nodeData?.data?.text || "",
          timestamp: new Date().toISOString(),
        });
      } catch (error) {
        console.error("删除节点时出错:", error);
        // 发送错误事件
        this.$emit("node-context-menu-action", {
          action: "deleteNodeWithChildren",
          nodeId: this.currentRightClickNode?.uid || null,
          error: error.message,
          timestamp: new Date().toISOString(),
        });
      } finally {
        this._hideContextMenu();
      }
    },

    // 仅删除当前节点（保留子节点）
    _deleteCurrentNodeOnly() {
      if (!this.currentRightClickNode) {
        console.warn("无法删除当前节点：当前节点为空");
        return;
      }

      try {
        const currentNode = this.currentRightClickNode;

        // 检查是否为根节点
        if (currentNode.isRoot) {
          console.warn("无法删除根节点");
          // 发送根节点删除限制事件
          this.$emit("node-context-menu-action", {
            action: "deleteCurrentNodeOnly",
            nodeId: currentNode.uid,
            nodeText: currentNode.nodeData?.data?.text || "",
            warning: "无法删除根节点",
            timestamp: new Date().toISOString(),
          });
          return;
        }

        // 激活当前节点
        this.mindMapInstance.renderer.activeNodeList = [currentNode];

        // 使用 REMOVE_CURRENT_NODE 命令仅删除当前节点
        this.mindMapInstance.execCommand("REMOVE_CURRENT_NODE");

        // 发送emit事件通知父组件
        this.$emit("node-context-menu-action", {
          action: "deleteCurrentNodeOnly",
          nodeId: currentNode.uid,
          nodeText: currentNode.nodeData?.data?.text || "",
          timestamp: new Date().toISOString(),
        });
      } catch (error) {
        console.error("删除当前节点时出错:", error);
        // 发送错误事件
        this.$emit("node-context-menu-action", {
          action: "deleteCurrentNodeOnly",
          nodeId: this.currentRightClickNode?.uid || null,
          error: error.message,
          timestamp: new Date().toISOString(),
        });
      } finally {
        this._hideContextMenu();
      }
    },

    // 清除节点内联样式的辅助方法
    _clearNodeInlineStyles(nodeElement) {
      if (!nodeElement) return;
      console.log(nodeElement);
      // 清除节点容器的样式
      nodeElement.style.opacity = "";

      // 清除形状元素的样式
      const shapeElement = nodeElement.querySelector(".smm-node-shape");
      if (shapeElement) {
        shapeElement.style.transform = "";
        shapeElement.style.boxShadow = "";
        shapeElement.style.stroke = "";
        shapeElement.style["stroke-width"] = 0;

        shapeElement.style.zIndex = "";
        shapeElement.style.filter = "";
      }

      // 清除文本元素的样式
      const textElement = nodeElement.querySelector(".smm-node-text");
      if (textElement) {
        textElement.style.fontWeight = "";
        textElement.style.color = "";
      }
    },

    // ======= 高亮API方法 =======

    // API 方法：按照节点id高亮指定节点 (支持字符串或数组)
    highlightNodeByNodeId(targetNodeIds) {
      if (!this.mindMapInstance) return;

      // 清除之前的高亮
      this.clearHighlight();

      try {
        const result = this._findNodesByCondition(
          { type: "id", value: targetNodeIds },
          false
        );

        if (result.targetNodes.length === 0) {
          console.warn("未找到目标节点:", targetNodeIds);
          return;
        }

        this._applyHighlight(result.highlightNodeIds, result.allNodes);
      } catch (error) {
        console.error("按节点ID高亮时出错:", error);
      }
    },

    // API 方法：按照节点id高亮指定节点及其子节点(支持字符串或数组)
    highlightNodeAndChildrenByNodeId(targetNodeIds) {
      if (!this.mindMapInstance) return;

      // 清除之前的高亮
      this.clearHighlight();

      try {
        const result = this._findNodesByCondition(
          { type: "id", value: targetNodeIds },
          true
        );

        if (result.targetNodes.length === 0) {
          console.warn("未找到目标节点:", targetNodeIds);
          return;
        }

        this._applyHighlight(result.highlightNodeIds, result.allNodes);
      } catch (error) {
        console.error("按节点ID高亮节点及其子节点时出错:", error);
      }
    },

    // API 方法：按照节点名称高亮指定节点 (支持字符串或数组)
    highlightNodeByNodeName(targetNodeNames) {
      if (!this.mindMapInstance) return;

      // 清除之前的高亮
      this.clearHighlight();

      try {
        const result = this._findNodesByCondition(
          { type: "name", value: targetNodeNames },
          false
        );

        if (result.targetNodes.length === 0) {
          console.warn("未找到目标节点:", targetNodeNames);
          return;
        }

        this._applyHighlight(result.highlightNodeIds, result.allNodes);
      } catch (error) {
        console.error("按节点名称高亮时出错:", error);
      }
    },

    // API 方法：按照节点名称高亮指定节点及其子节点 (支持字符串或数组)
    highlightNodeAndChildrenByNodeName(targetNodeNames) {
      if (!this.mindMapInstance) return;

      // 清除之前的高亮
      this.clearHighlight();

      try {
        const result = this._findNodesByCondition(
          { type: "name", value: targetNodeNames },
          true
        );

        if (result.targetNodes.length === 0) {
          console.warn("未找到目标节点:", targetNodeNames);
          return;
        }

        this._applyHighlight(result.highlightNodeIds, result.allNodes);
      } catch (error) {
        console.error("按节点名称高亮节点及其子节点时出错:", error);
      }
    },

    // API 方法：按类型高亮节点(支持字符串或数组)
    highlightNodeByType(targetType) {
      if (!targetType || !this.mindMapInstance) return;

      // 清除之前的高亮
      this.clearHighlight();

      try {
        const result = this._findNodesByCondition(
          { type: "type", value: targetType },
          false
        );

        if (result.targetNodes.length === 0) {
          console.warn("未找到目标类型的节点:", targetType);
          return;
        }

        this._applyHighlight(result.highlightNodeIds, result.allNodes);
      } catch (error) {
        console.error("按类型高亮时出错:", error);
      }
    },

    // API 方法：按类型高亮节点及其子节点（支持字符串或数组）
    highlightNodeAndChildrenByType(targetType) {
      if (!targetType || !this.mindMapInstance) return;

      // 清除之前的高亮
      this.clearHighlight();

      try {
        const result = this._findNodesByCondition(
          { type: "type", value: targetType },
          true
        );

        if (result.targetNodes.length === 0) {
          console.warn("未找到目标类型的节点:", targetType);
          return;
        }

        this._applyHighlight(result.highlightNodeIds, result.allNodes);
      } catch (error) {
        console.error("按类型高亮节点及其子节点时出错:", error);
      }
    },

    // API 方法：清除高亮效果
    clearHighlight() {
      if (!this.mindMapInstance) return;

      try {
        const cache = this.nodeCache;
        cache.allNodes.forEach((node) => {
          const nodeElement = node.group?.node;
          if (nodeElement) {
            // 清除CSS类
            nodeElement.classList.remove("node-highlighted");
            nodeElement.classList.remove("node-dimmed");

            // 清除内联样式
            this._clearNodeInlineStyles(nodeElement);

            // 清除自定义属性
            nodeElement.removeAttribute("data-highlight-state");
          }
        });

        this.highlightedNodes.clear();
      } catch (error) {
        console.error("清除高亮时出错:", error);
      }
    },

    // API 方法：按层级展示节点
    showByLevel(level) {
      if (!this.mindMapInstance) return;

      try {
        const root = this.mindMapInstance.renderer?.root;
        if (!root) {
          console.warn("根节点不可用");
          return;
        }

        if (level === "all") {
          // 全部展开
          this.mindMapInstance.command.exec("EXPAND_ALL");
          return;
        }

        const targetLevel = parseInt(level);
        if (isNaN(targetLevel)) return;

        this.mindMapInstance.execCommand("UNEXPAND_TO_LEVEL", targetLevel);
      } catch (error) {
        console.error("按层级展示时出错:", error);
      }
    },

    // ======= 节点管理API方法 =======

    // API 方法：添加单个节点
    addNode(nodeData, parentNodeId = null) {
      try {
        if (!this.mindMapInstance) {
          console.error("添加节点失败: 思维导图实例未初始化");
          return false;
        }

        // 验证节点数据
        const nodeValidation = this._validateNodeData(nodeData);
        if (!nodeValidation.valid) {
          console.error("添加节点失败:", nodeValidation.error);
          return false;
        }

        if (parentNodeId) {
          // 查找父节点
          const parentNode =
            this.mindMapInstance.renderer.findNodeByUid(parentNodeId);
          if (!parentNode) {
            console.error("添加节点失败: 父节点不存在", parentNodeId);
            return false;
          }

          // 激活父节点
          this.mindMapInstance.renderer.activeNodeList = [parentNode];

          // 使用库原生API添加子节点
          this.mindMapInstance.execCommand("INSERT_CHILD_NODE", false, [], {
            uid: nodeData.id,
            text: nodeData.label,
            type: nodeData.type,
            data: {
              ...nodeData, // 支持其他自定义属性
            },
          });
        } else {
          // 如果没有指定父节点，添加为根节点的子节点
          const rootNode = this.mindMapInstance.renderer.root;
          if (rootNode) {
            this.mindMapInstance.renderer.activeNodeList = [rootNode];
            this.mindMapInstance.execCommand("INSERT_CHILD_NODE", false, [], {
              uid: nodeData.id,
              text: nodeData.label,
              type: nodeData.type,
              data: {
                ...nodeData,
              },
            });
          } else {
            console.error("添加节点失败: 无法找到根节点");
            return false;
          }
        }

        // 注意：样式会在 node_tree_render_end 事件中统一应用
        return true;
      } catch (error) {
        console.error("添加节点时出错:", error);
        return false;
      }
    },

    // API 方法：批量添加节点
    addNodes(nodesData) {
      try {
        if (!this.mindMapInstance) {
          console.error("批量添加节点失败: 思维导图实例未初始化");
          return false;
        }

        if (!Array.isArray(nodesData)) {
          console.error("添加节点失败: nodesData必须是数组");
          return false;
        }

        if (nodesData.length === 0) {
          console.warn("没有节点需要添加");
          return true;
        }

        // 预先验证所有节点数据
        for (const nodeConfig of nodesData) {
          const { nodeData } = nodeConfig;
          const nodeValidation = this._validateNodeData(nodeData);
          if (!nodeValidation.valid) {
            console.error("批量添加节点失败:", nodeValidation.error, nodeData);
            return false;
          }
        }

        let successCount = 0;
        const failedNodes = [];

        // 逐个添加节点
        for (const nodeConfig of nodesData) {
          const { nodeData, parentNodeId = null } = nodeConfig;

          try {
            if (parentNodeId) {
              // 查找父节点
              const parentNode =
                this.mindMapInstance.renderer.findNodeByUid(parentNodeId);
              if (!parentNode) {
                console.error(
                  "跳过节点添加: 父节点不存在",
                  parentNodeId,
                  nodeData.id
                );
                failedNodes.push({ nodeData, reason: "父节点不存在" });
                continue;
              }

              // 激活父节点并添加子节点
              this.mindMapInstance.renderer.activeNodeList = [parentNode];
              this.mindMapInstance.execCommand("INSERT_CHILD_NODE", false, [], {
                uid: nodeData.id,
                text: nodeData.label,
                type: nodeData.type,
                data: {
                  ...nodeData,
                },
              });
            } else {
              // 添加为根节点的子节点
              const rootNode = this.mindMapInstance.renderer.root;
              if (rootNode) {
                this.mindMapInstance.renderer.activeNodeList = [rootNode];
                this.mindMapInstance.execCommand(
                  "INSERT_CHILD_NODE",
                  false,
                  [],
                  {
                    uid: nodeData.id,
                    text: nodeData.label,
                    type: nodeData.type,
                    data: {
                      ...nodeData,
                    },
                  }
                );
              } else {
                failedNodes.push({ nodeData, reason: "无法找到根节点" });
                continue;
              }
            }

            successCount++;
          } catch (error) {
            console.error("添加单个节点失败:", error, nodeData.id);
            failedNodes.push({ nodeData, reason: error.message });
          }
        }

        return failedNodes.length === 0;
      } catch (error) {
        console.error("批量添加节点时出错:", error);
        return false;
      }
    },

    // API 方法：删除单个或多个节点
    removeNode(nodeIds, removeChildren = false) {
      try {
        if (!this.mindMapInstance) {
          console.error("删除节点失败: 思维导图实例未初始化");
          return false;
        }

        // 统一处理单个ID或ID数组
        const targetNodeIds = Array.isArray(nodeIds) ? nodeIds : [nodeIds];

        if (targetNodeIds.length === 0 || targetNodeIds.some((id) => !id)) {
          console.error("删除节点失败: 节点ID不能为空");
          return false;
        }

        const nodesToDelete = [];
        const failedNodes = [];

        // 查找所有要删除的节点
        targetNodeIds.forEach((nodeId) => {
          const node = this.mindMapInstance.renderer.findNodeByUid(nodeId);
          if (node) {
            nodesToDelete.push(node);
          } else {
            failedNodes.push({ nodeId, reason: "节点不存在" });
          }
        });

        if (nodesToDelete.length === 0) {
          console.error("删除节点失败: 所有指定的节点都不存在");
          return false;
        }

        // 激活要删除的节点
        this.mindMapInstance.renderer.activeNodeList = nodesToDelete;

        // 使用库原生API删除节点
        if (removeChildren) {
          // 删除节点及其所有子节点
          this.mindMapInstance.execCommand("REMOVE_NODE");
        } else {
          // 只删除当前节点，保留子节点
          this.mindMapInstance.execCommand("REMOVE_CURRENT_NODE");
        }

        return failedNodes.length === 0;
      } catch (error) {
        console.error("删除节点时出错:", error);
        return false;
      }
    },

    // API 方法：编辑单个节点
    editNode(nodeId, updateData) {
      try {
        if (!this.mindMapInstance) {
          console.error("编辑节点失败: 思维导图实例未初始化");
          return false;
        }

        if (!nodeId) {
          console.error("编辑节点失败: 节点ID不能为空");
          return false;
        }

        if (!updateData || typeof updateData !== "object") {
          console.error("编辑节点失败: 更新数据必须是一个对象");
          return false;
        }

        // 不允许修改节点ID
        if (Object.prototype.hasOwnProperty.call(updateData, "id")) {
          console.error("编辑节点失败: 不允许修改节点ID");
          return false;
        }

        // 查找节点实例
        const targetNode = this.mindMapInstance.renderer.findNodeByUid(nodeId);
        if (!targetNode) {
          console.error("编辑节点失败: 节点不存在", nodeId);
          return false;
        }

        // 验证label字段
        if (Object.prototype.hasOwnProperty.call(updateData, "label")) {
          if (!updateData.label || typeof updateData.label !== "string") {
            console.error("编辑节点失败: label必须是非空字符串");
            return false;
          }
        }

        // 激活节点
        this.mindMapInstance.execCommand("SET_NODE_DATA", targetNode, {
          type: updateData.type,
          text: updateData.label,
        });

        // 重新渲染节点
        this.mindMapInstance.render();
        // 注意：样式会在 node_tree_render_end 事件中统一应用

        return true;
      } catch (error) {
        console.error("编辑节点时出错:", error);
        return false;
      }
    },

    // 获取当前数据
    getCurrentData() {
      return this.internalMindMapData;
    },

    // 思维导图实例访问
    getMindMapInstance() {
      return this.mindMapInstance;
    },
  },
};
</script>

<style scoped lang="scss">
.mind-map-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  font-family: "Alibaba PuHuiTi", "Arial", sans-serif;
}

.mind-map-canvas {
  flex: 1;
  position: relative;
  overflow: hidden;
  border-radius: 0 0 12px 12px;
  background-color: rgb(207 216 231) !important;
}

// 自定义思维导图样式
:deep(.smm-node) {
  font-family: "Alibaba PuHuiTi", "Arial", sans-serif;

  // 根节点样式
  &.smm-node-root {
    .smm-node-shape {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }

  // 一级节点样式
  &.smm-node-generalization {
    .smm-node-shape {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }

  // 高亮节点样式
  &.node-highlighted {
    .smm-node-shape {
      transform: scale(1.05) !important;
      box-shadow: 0 6px 20px rgba(255, 255, 255, 1) !important;
      stroke: #fff !important;
      z-index: 10 !important;
    }

    .smm-node-text {
      font-weight: 700 !important;
      color: #2b6cb0 !important;
    }
  }

  // 弱化节点样式
  &.node-dimmed {
    opacity: 0.3 !important;

    .smm-node-shape {
      filter: grayscale(0.5) !important;
      transform: scale(0.95) !important;
    }

    .smm-node-text {
      color: #a0aec0 !important;
    }
  }
}

// 通过自定义属性进行高亮样式设置（只读模式的备选方案）
:deep(.smm-node[data-highlight-state="highlighted"]) {
  .smm-node-shape {
    transform: scale(1.05) !important;
    box-shadow: 0 6px 20px rgba(255, 255, 255, 1) !important;
    stroke: #fff !important;
    z-index: 10 !important;
  }

  .smm-node-text {
    font-weight: 700 !important;
    color: #2b6cb0 !important;
  }
}

:deep(.smm-node[data-highlight-state="dimmed"]) {
  opacity: 0.3 !important;

  .smm-node-shape {
    filter: grayscale(0.5) !important;
    transform: scale(0.95) !important;
  }

  .smm-node-text {
    color: #a0aec0 !important;
  }
}

// 强制隐藏所有可能的文本编辑框
:deep(.smm-text-edit),
:deep(.smm-text-edit-input),
:deep(.smm-text-edit-textarea),
:deep([class*="text-edit"]),
:deep([class*="textEdit"]) {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
}

// 右键菜单样式
.context-menu {
  position: fixed;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  z-index: 1000;
  min-width: 180px;
  padding: 8px 0;
  font-family: "Alibaba PuHuiTi", "Arial", sans-serif;
  user-select: none;

  .context-menu-item {
    display: flex;
    align-items: center;
    padding: 10px 16px;
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;
    background: none;
    width: 100%;
    text-align: left;
    font-size: 14px;
    color: #4a5568;

    &:hover {
      background-color: #f7fafc;
      color: #2d3748;
    }

    &.danger {
      color: #e53e3e;

      &:hover {
        background-color: #fed7d7;
        color: #c53030;
      }
    }

    .menu-icon {
      margin-right: 12px;
      font-size: 16px;
      width: 20px;
      text-align: center;
      flex-shrink: 0;
    }

    .menu-text {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .context-menu-divider {
    height: 1px;
    background-color: #e2e8f0;
    margin: 8px 0;
  }
}
</style>
